<script lang="ts" setup>
import {useRoute} from 'vue-router'
import {ref} from "vue"
import {getByIdAdminSysUser, putAdminSysUser, userRegister} from "../serve"
import {ElMessage} from "element-plus"

const
    route = useRoute(),
    fromData: any = ref({
      username: '',
      password: ''
    }),
    loading = ref(false),
    isAdd = ref(false),
    fromRules = {
      username: [
        {
          required: true,
          min: 1,
          max: 15,
          message: '账号长度1-15位',
          trigger: 'trigger',
        },
      ],
      password: [
        {
          required: true,
          min: 1,
          max: 20,
          message: '密码长度1-20位',
          trigger: 'trigger',
        },
      ]
    },
    froms = ref()
;

function get() {
  if (route.query['id']) {
    loading.value = true
    isAdd.value = false
    getByIdAdminSysUser(route.query['id']).then((r: any) => {
      fromData.value = r
      loading.value = false
    }).catch(() => loading.value = false)
  } else {
    isAdd.value = true
  }
}

get()

async function change() {
  try {
    await froms.value.validate()
    loading.value = true
    if (isAdd.value) {
      userRegister({...fromData.value}).then(() => {
        loading.value = false
        ElMessage({type: 'success', message: '新增成功！'})
      }).catch(() => loading.value = false)
      return
    }
    putAdminSysUser({...fromData.value}).then(() => {
      ElMessage({type: 'success', message: '修改成功！'})
      get()
    }).catch(() => loading.value = false)
  } catch (e) {
  }
}

</script>

<template>
  <el-scrollbar>
    <el-card v-loading="loading" box element-loading-text="加载中...">
      <template #header>{{ isAdd ? '管理员添加' : '编辑信息' }}</template>
      <el-form ref="froms" :model="fromData" :rules="fromRules" el-From>
        <el-form-item label="账号：" prop="username">
          <el-input v-model="fromData['username']" maxlength="15" placeholder="请输入账号"/>
        </el-form-item>
        <el-form-item label="密码：" prop="password">
          <el-input v-model="fromData['password']" maxlength="20" placeholder="请输入密码" show-password
                    type="password"/>
        </el-form-item>
        <el-form-item>
          <el-button round style="width: 80%;margin: auto;" type="success" @click="change">立即提交</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </el-scrollbar>
</template>

<style lang="scss" scoped>
[box] {
  width: 50%;
  margin: auto;
}

[el-From] {
  width: 98%;
  margin: auto;
}
</style>